package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
@Slf4j
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId, Long friendId) {
        //保存自己的好友数据
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("friendId").is(friendId);
        Query query = Query.query(criteria);
        boolean exists = mongoTemplate.exists(query, Friend.class);
        if (!exists) {
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        //保存好友的数据
        Criteria criteria1 = Criteria.where("userId").is(friendId)
                .and("friendId").is(userId);
        Query query1 = Query.query(criteria1);
        boolean exists1 = mongoTemplate.exists(query1, Friend.class);

        if (!exists1) {
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }

    @Override
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria)
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Friend.class);
    }

    @Override
    public void delete(Long userId, Long disLikeUserId) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("friendId").is(disLikeUserId);
        mongoTemplate.remove(Query.query(criteria),Friend.class);
        Criteria criteria2 = Criteria.where("userId").is(disLikeUserId)
                .and("friendId").is(userId);
        mongoTemplate.remove(Query.query(criteria2),Friend.class);
    }

    /*
    * 查询所有好友
    * */
    @Override
    public Integer findByUserId(Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        return Math.toIntExact(mongoTemplate.count(query, Friend.class));
    }
}
